package com.sample.library.util;

import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * 系统工具类
 * Created by tankai on 2015/11/4.
 */
public class SystemUtil {

    private static final String TAG = "SystemUtils";
    //剪切板或apk包中渠道号
    private static String appChannel;
    //答题渠道号
    private static String appActChannel;

    /**
     * 得到全局唯一UUID
     */
    public static String getUUID(Context context) {
        return UUID.randomUUID().toString();
    }

    /**
     * 跳转应用设置详情页
     *
     * @param context
     */
    public static void goSetting(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        context.startActivity(localIntent);
    }

    /**
     * 获取本应用的版本号
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    /**
     * 获取本应用的VersionCode
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int versioncode = -1;
        try {
            versioncode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versioncode;
    }

    /**
     * 获取本机渠道标识
     *
     * @param context
     * @param prefix
     * @return
     */
    public static String getChannel(Context context, String prefix) {

        if (TextUtils.isEmpty(appChannel)) {
            //剪切板没有，读取apk包中的渠道号
            ApplicationInfo appinfo = context.getApplicationInfo();
            String sourceDir = appinfo.sourceDir;
            String ret = "";
            ZipFile zipfile = null;
            try {
                zipfile = new ZipFile(sourceDir);
                Enumeration<?> entries = zipfile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = ((ZipEntry) entries.nextElement());
                    String entryName = entry.getName();
                    if (entryName.contains(prefix)) {
                        ret = entryName;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (zipfile != null) {
                    try {
                        zipfile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (ret.contains(prefix)) {
                appChannel = ret.substring(ret.indexOf("_") + 1);
            } else {
                appChannel = "0";
            }
        } else {
            appChannel = "0";
        }

        return appChannel;

    }

    /**
     * 复制文字到剪切板
     *
     * @param context
     * @param content
     */
    public static void copyTextToClip(Context context, String content) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", content);
        clipboard.setPrimaryClip(clip);
    }

    /**
     * 从剪切板获取邀请id
     *
     * @param context
     * @return
     */
    public static String getChannelFromClip(Context context) {
        //格式
        //QireReader:Invitation:123456
        String channel = "";
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboardManager == null) {
            return channel;
        }
        if (!clipboardManager.hasPrimaryClip()) {
            return channel;
        }
        ClipData clipData = clipboardManager.getPrimaryClip();
        if (clipData == null) {
            return channel;
        }
        for (int i = 0; i < clipData.getItemCount(); i++) {
            ClipData.Item item = clipData.getItemAt(i);
            if (item != null && !TextUtils.isEmpty(item.getText())) {
                String text = item.getText().toString();
                if (!TextUtils.isEmpty(text) && text.contains("QireReader:Invitation")) {
                    String[] strings = text.split(":");
                    if (strings.length == 3) {
                        return strings[2];
                    }
                }
            }
        }
        return channel;
    }

    public static boolean fileIsExists(String path) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(path);
            return file.exists();
        }
        return false;
    }

    public static boolean isWeixinAvilible(Context context) {
        try {
            final PackageManager packageManager = context.getPackageManager();
            // 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
            // 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.tencent.mm")) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;

    }

    /**
     * 跳转指定QQ号
     *
     * @param context
     * @param qq
     */
    public static void openQQ(Context context, String qq) {

        try {
            String url;
            if (TextUtils.isEmpty(qq)) {
                url = "mqqwpa://im/chat?chat_type=wpa&uin=613276213";
            } else {
                url = "mqqwpa://im/chat?chat_type=wpa&uin=".concat(qq);
            }
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "请安装QQ", Toast.LENGTH_SHORT).show();
        }

    }

    /****************
     *
     * 发起添加群流程。群号：奇热小说交流群(528487060) 的 key 为： 6My5JaKoMGYz0Jaa_Rc8_tLe7FO0S6v-
     * 调用 joinQQGroup(6My5JaKoMGYz0Jaa_Rc8_tLe7FO0S6v-) 即可发起手Q客户端申请加群 奇热小说交流群(528487060)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
     ******************/
    public static boolean joinQQGroup(Context context, String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            Toast.makeText(context, "请安装QQ", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 打开微信
     *
     * @param context
     */
    public static void openWechat(Context context) {

        try {
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "请安装微信", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 跳转应用市场
     */
    public static void goMarket(Context context) {
        try {
            Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "您没有安装应用市场", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 判断应用是否已经启动
     *
     * @param context     一个context
     * @param packageName 要判断应用的包名
     * @return boolean
     */
    public static boolean isAppAlive(Context context, String packageName) {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses();
        for (int i = 0; i < processInfos.size(); i++) {
            if (processInfos.get(i).processName.equals(packageName)) {
                //app进程存在
                return true;
            }
        }
        //app还没启动
        return false;
    }

    public static void showSoftKeyboard(Context mContext, View view) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取json
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getAssetsJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 解决oppoR9 TimeoutExceptions
     */
    public static void fixOPPOTimeout() {
        try {
            Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");
            Method method = clazz.getSuperclass().getDeclaredMethod("stop");
            method.setAccessible(true);
            Field field = clazz.getDeclaredField("INSTANCE");
            field.setAccessible(true);
            method.invoke(field.get(null));
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void writeTxtToFile(String strcontent) {

        File m = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "Android");
        if (!m.exists()) {
            m.mkdir();
        }
        String path = Environment.getExternalStorageDirectory().getPath() + File.separator
                + "Android" + File.separator + ".kaixing_";
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strcontent.getBytes());
            raf.close();
        } catch (IOException e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    //读取指定目录下的所有TXT文件的文件内容
    public static String getFileContent() {
        String path = Environment.getExternalStorageDirectory().getPath() + File.separator
                + "Android" + File.separator + ".kaixing_";
        File file = new File(path);
        StringBuilder content = new StringBuilder();
        try {
            InputStream instream = new FileInputStream(file);
            InputStreamReader inputreader
                    = new InputStreamReader(instream, StandardCharsets.UTF_8);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line = "";
            //分行读取
            while ((line = buffreader.readLine()) != null) {
                content.append(line).append("\n");
            }
            instream.close();

        } catch (IOException e) {
            Log.d("TestFile", e.getMessage());
        }
        return content.toString();
    }

    public static String getAppMetaData(Context context) {
        if (context == null) {
            return null;
        }
        String channelNumber = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo.metaData != null) {
                    channelNumber = applicationInfo.metaData.getString("UMENG_CHANNEL");
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelNumber;
    }

    public static boolean copyFile(String srcPath, String destPath) {
        boolean flag = false;
        File srcFile = new File(srcPath); // 源文件
        if (!srcFile.exists()) {
            Log.i("FileUtils is copyFile：", "源文件不存在");
            return false;
        }
        if (destPath.equals(srcPath)) {
            Log.i("FileUtils is copyFile：", "源文件路径和目标文件路径重复");
            return false;
        }
        File destFile = new File(destPath); // 目标文件
        if (destFile.exists() && destFile.isFile()) {
            Log.i("FileUtils is copyFile：", "该路径下已经有一个同名文件");
            return false;
        }
        try {
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fis.close();
            fos.close();
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }



}
